﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Europrog.Windows.Resx2xlsx.BusinessObjects;
using System.Resources;
using System.IO;
using System.Collections;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Globalization;
using System.Collections.ObjectModel;




namespace Europrog.Windows.Resx2xlsx.ServiceLogic
{
    public static class ResxParser
    {
        public static Collection<ResourceObject> ExtractFromFile(string filePath)
        {
            Collection<ResourceObject> returnValue = new Collection<ResourceObject>();
            if (File.Exists(filePath))
            {

                using (ResXResourceReader resxReader = new ResXResourceReader(filePath))
                {
                    try
                    {
                        resxReader.UseResXDataNodes = true;

                        foreach (DictionaryEntry item in resxReader)
                        {
                            ResourceObject returnValueItem = new ResourceObject()
                            {
                                Name = item.Key.ToString(),
                                Value = (item.Value as ResXDataNode).GetValue((ITypeResolutionService)null).ToString(),
                                Comment = (item.Value as ResXDataNode).Comment
                            };

                            returnValue.Add(returnValueItem);
                        }
                    }
                    finally
                    {
                        resxReader.Close();
                    }
                }
            }
            else
            {
                throw new FileNotFoundException(string.Format("The filePath parameter as {0} cannot be located", filePath));
            }
            return returnValue;
        }
        
        public static string CreateResource(string resourceFile, string cultureInfo)
        {
            string returnValue = string.Empty;

            // Ensure that the file exists
            if (!File.Exists(resourceFile))
            {
                throw new FileNotFoundException();
            }
            if (!Path.GetExtension(resourceFile).ToLowerInvariant().Equals(".resx"))
            {
                throw new Exception("Wrong file name, it must be a resource file with .resx extension");
            }
            
            // Getting the Resource file's folder
            string resourceFileFolder = Path.GetDirectoryName(resourceFile);

            // Getting the filename so that the new fileName can be generated
            string fileName = Path.GetFileNameWithoutExtension(resourceFile);
            string newFileName = string.Format("{0}.{1}.resx", fileName, cultureInfo);

            // Opening the new localized file by ResXResourceWriter
            string newFullPath = Path.Combine(resourceFileFolder, newFileName);

            // List for storing the keys from the destination resource file. It is because those ones must not be inserted again.
            List<string> keysInDestinationResource = new List<string>();

            // Fetching the nodes from the new file if it is already exists
            GetAlreadyStoredResourceNodes(newFullPath, keysInDestinationResource);

            // Generate new resource file based on te original file
            GenerateNewResourceFile(resourceFile, newFullPath, keysInDestinationResource);
            returnValue = newFullPath;
            return returnValue;
        }

       

       
      

      
        private static List<string> GetCultureNames(string[] localizedFiles)
        {
            List<string> cultureNames = new List<string>();
            foreach (var item in localizedFiles)
            {
                var splittedItems = item.Split(new char[] { '.' });
                if (splittedItems.Count() == 3)
                {
                    cultureNames.Add(splittedItems[1]);
                }
            }
            return cultureNames;
        }

        public static string[] GetLocalizedFiles(string resourceName)
        {
            string[] localizedFiles;
            var directoryName = Path.GetDirectoryName(resourceName);
            var resourceFileName = Path.GetFileNameWithoutExtension(resourceName);
            localizedFiles = Directory.GetFiles(directoryName, string.Format("{0}.*.resx", resourceFileName));
            return localizedFiles;
        }

        public static bool ReWriteResourceFile(string pathToResourceFile, Dictionary<string, Tuple<string, string>> resourceItems)
        {
            if (File.Exists(pathToResourceFile))
            {
                try
                {
                    File.Delete(pathToResourceFile);
                }
                catch (Exception ex)
                {

                }
            }
            using (ResXResourceWriter resXResourceWriter = new ResXResourceWriter(pathToResourceFile))
            {               
                try
                {                    
                    foreach (var item in resourceItems)
                    {
                        resXResourceWriter.AddResource(new ResXDataNode(item.Key, item.Value.Item1) { Comment = item.Value.Item2 });
                    }
                    resXResourceWriter.Generate();                    
                }
                catch (Exception ep)
                {
                    return false;
                }
                finally
                {
                    resXResourceWriter.Close();
                }
            }
            return true;
                
        }

        #region private methods
        private static void GenerateNewResourceFile(string resourceFile, string newFullPath, List<string> keysInDestinationResource)
        {
            using (ResXResourceWriter resXResourceWriter = new ResXResourceWriter(newFullPath))
            {
                // Opening the original resource to copy the resource nodes to the new localized resource file.
                using (ResXResourceReader resXResourceReader = new ResXResourceReader(resourceFile))
                {
                    try
                    {
                        resXResourceReader.UseResXDataNodes = true;
                        foreach (DictionaryEntry item in resXResourceReader)
                        {
                            if (!keysInDestinationResource.Contains(item.Key.ToString()))
                            {
                                resXResourceWriter.AddResource(item.Value as ResXDataNode);
                            }
                        }
                        resXResourceWriter.Generate();
                    }
                    finally
                    {
                        resXResourceWriter.Close();
                        resXResourceReader.Close();
                    }
                }
            }
        }

        private static void GetAlreadyStoredResourceNodes(string newFullPath, List<string> keysInDestinationResource)
        {
            // if the file does not exist then we dont need to check it
            if (File.Exists(newFullPath))
            {
                // Collecting the previously stored resource entries
                using (ResXResourceReader resXResourceReader = new ResXResourceReader(newFullPath))
                {
                    try
                    {
                        resXResourceReader.UseResXDataNodes = true;
                        foreach (DictionaryEntry item in resXResourceReader)
                        {
                            keysInDestinationResource.Add(item.Key.ToString());
                        }
                    }
                    finally
                    {
                        resXResourceReader.Close();
                    }
                }
            }
        }
              
        #endregion
    }
}
